package mx.com.mindbits.bandpay;


import mx.com.bancogato.fingersign.DrawView;
import mx.com.mindbits.bandpay.utils.ConstantsValues;
import mx.com.mindbits.bandpay.utils.GenericAlert;
import mx.com.mindbits.bandpay.utils.LayoutToImg;
import mx.com.mindbits.bandpay.utils.ShakeDetector;
import mx.com.mindbits.bandpay.utils.ShakeDetector.OnShakeListener;
import mx.com.mindbits.bandpay.utils.Utils;
import mx.com.mindbits.bandpay.vo.SignSave;
import mx.com.mindbits.bandpay.vo.TAECompraVO;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

public class FingerSignature extends SherlockActivity  {	
	private DrawView drawView;
	private ShakeDetector mShakeDetector;
    private SensorManager mSensorManager;
    private Sensor mAccelerometer;
    private Intent toFinishActivity;
    private Bundle bundleReceived;
    
    private TAECompraVO lastCompra;
    private String arqcPersistance;
    private String aidPersistance;
    
    private Menu menu;
    private MenuItem itemClean;
    private MenuItem itemContinue;
    private Button btClean;
    private Button btContinue;
    
    private BroadcastR broadcast;
    private Context context;
    

    public Menu getMenu() {
		return menu;
	}
	public void setMenu(Menu menu) {
		this.menu = menu;
	}
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		// Set full screen view
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);       
        //shake method to erase the screen
        OnShakeListener sl = new OnShakeListener() {
            @Override
            public void onShake() {
                drawView.clearPoints();
               if(btContinue.isEnabled())
                	btContinue.setEnabled(false);
               		btContinue.setBackgroundResource(R.drawable.button_disable_shape);
            }
        };
        //////////set context//////////////////////
        context = getApplicationContext();
        
        ///////////////Broadcast//////////////
        IntentFilter filter = new IntentFilter("UPDATE");
        broadcast = new BroadcastR();
        registerReceiver(broadcast, filter);
        
		//menu.findItem(R.id.finishSell).setEnabled(false);
        bundleReceived = this.getIntent().getExtras();
    	getLastProduct();
        //try to put in a static class configuration params like this
    	    	
        drawView = new DrawView(this,setStringDescription());
        setContentView(drawView);
        drawView.setBackgroundColor(Color.WHITE);
        drawView.requestFocus();        
        //ShakeDetector initialization
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mShakeDetector = new ShakeDetector(sl);
        
		//
        ActionBar aboj = getSupportActionBar();//getActionBar();        
        aboj.setDisplayHomeAsUpEnabled(true);
        
	}
	public String[] setStringDescription(){
		String[] elementos = new String[5];
		 elementos[0] = context.getResources().getString(R.string.form_fieldmount) + " " +
		Utils.setFloatFormat(Float.parseFloat(lastCompra.getMonto()));
		 elementos[1] = context.getResources().getString(R.string.title_descripcion);
		 if(!lastCompra.getNumbertae().isEmpty()){//TAE
			 Log.i("teclas", "desv_ " + lastCompra.getProducto());
			 if(!lastCompra.getProducto().isEmpty())
				 elementos[2] = lastCompra.getProducto();
			 else
				 elementos[2] = "Tiempo aire";
			 
			 	 elementos[3] = context.getResources().getString(R.string.form_fieldphone);
				 elementos[4] = lastCompra.getNumbertae(); 
		 }else{
			 if(!lastCompra.getProducto().isEmpty())
				 elementos[2] = lastCompra.getProducto();
			 else
				 elementos[2] = "Pago generico";
		 
		 	 elementos[3] = "";
			 elementos[4] = lastCompra.getNumbertae(); 
		 }
		return elementos;
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		setMenu(menu);
		getSupportMenuInflater().inflate(R.menu.activity_finger_signature, menu);
		itemClean = (MenuItem) menu.findItem(R.id.clear_finger);
		itemContinue =(MenuItem) menu.findItem(R.id.finishSell);
		btContinue = (Button) itemContinue.getActionView().findViewById(R.id.buttonGeneric);
		btContinue.setText(R.string.label_buttonbar_continuar);
		btContinue.setBackgroundResource(R.drawable.button_disable_shape);
		btContinue.setEnabled(false);
		btContinue.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				setFinishSell();
			}
			
		});
		btClean = (Button) itemClean.getActionView().findViewById(R.id.buttonGeneric);
		btClean.setText(R.string.form_cleanButton);
		btClean.setBackgroundResource(R.drawable.button_disable_shape);
		btClean.setEnabled(false);
		btClean.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v){
				setClearView();
			}
		});
		
		return true;
	}
	
	@Override
	  public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case android.R.id.home:
			Intent intent = new Intent(this, MainMenuActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(intent);
			break;
		//case R.id.clear_finger:
				//setClearView();
			//break;
		//case R.id.finishSell:
			//Log.d(ConstantsValues.TAG_DRAWSIGN, "Cantidad de puntos dibujados ["+drawView.showPoints()+"]");
			//setFinishSell();
									
			//break;
		default:
			break;
		}
		return false;
		  
	  }
	public void setClearView(){
		drawView.clearPoints();
		btContinue.setBackgroundResource(R.drawable.button_disable_shape);
	}
	
	
	public void setFinishSell(){
		SignSave.signatureBitmap  = LayoutToImg.getBitmapFromView(drawView);	
		toFinishActivity = new Intent(this, SendTicketActivity.class);
		bundleReceived.putSerializable("finalData", lastCompra);
		bundleReceived.putString("arqc", arqcPersistance);
		bundleReceived.putString("aid", aidPersistance);
		toFinishActivity.putExtras(bundleReceived);
		Log.d(ConstantsValues.TAG_DRAWSIGN, "Objeto colocado en bundle...");
		startActivity(toFinishActivity);
		Log.d(ConstantsValues.TAG_DRAWSIGN, "coloca la imagen de la firma en el ticket...");
	}
			
	public void getLastProduct(){
		if (bundleReceived != null){
		lastCompra = (TAECompraVO) bundleReceived.getSerializable("completeSell");
		arqcPersistance = bundleReceived.getString("arqc");
		aidPersistance  = bundleReceived.getString("aid");
		Log.d(ConstantsValues.TAG_DRAWSIGN, "Datos que han pasado");												
		Log.d(ConstantsValues.TAG_DRAWSIGN, "MONTO: ["+lastCompra.getMonto()+"]");
		Log.d(ConstantsValues.TAG_DRAWSIGN, "TELEFONO: ["+lastCompra.getNumbertae()+"]");
		Log.d(ConstantsValues.TAG_DRAWSIGN, "PRODUCTO: ["+lastCompra.getProducto()+"]");
		Log.d(ConstantsValues.TAG_DRAWSIGN, "PROVEEDOR: ["+lastCompra.getProveedor()+"]");
		Log.d(ConstantsValues.TAG_DRAWSIGN, "ARQC: ["+arqcPersistance+"]");
		}
	}
	 @Override
	    protected void onResume() {
	        super.onResume();
	        mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
	    }

	  @Override
	    protected void onPause() {
	        mSensorManager.unregisterListener(mShakeDetector);
	        super.onPause();
	    }

	  
	  
	private class BroadcastR extends BroadcastReceiver{

		@Override
		public void onReceive(Context arg0, Intent _intent) {
			// TODO Auto-generated method stub
			Bundle bundle = _intent.getExtras();
			int points = bundle.getInt("numPoints");
				if(points > 0){
					btContinue.setEnabled(true);//itemMenu.setEnabled(true);
					btContinue.setBackgroundResource(R.drawable.blue_button_shape);
					btClean.setEnabled(true);
                    btClean.setBackgroundResource(R.drawable.blue_button_shape);
				}
		}
		
	}
	
	@Override
	public void onBackPressed(){

		GenericAlert.generateAlertDialog(context.getString(R.string.app_name),
				context.getString(R.string.label_back), drawView.getContext()).show();
	}
	
}
